package sh.orm.convert;


import sh.orm.OrmException;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.*;
import java.util.Date;

/**
 * 日期类型转换器,把数据库类型转换为目标数据类型
 *
 * java.util.Date <-> date,datetime
 *
 * @author lqq
 * @date 2019/2/21
 */
public class DateTypeConvertor extends AbstractTypeConvertor<Date>{

    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public Date convert(Object original, Class targetType) {
        if(original == null){
            return null;
        }

        if(targetType == Date.class){
            return convertToDate(original);
        }

        throw new OrmException("暂不支持的目标日期类型转换" + targetType);
    }

    @Override
    public String convertToJdbcValue(Date javaObj) {
        return dateFormat.format(javaObj);
    }

    @Override
    public Date convertToJavaType(String columnName, ResultSet rs) {
        try {
            return rs.getDate(columnName);
        } catch (SQLException e) {
            throw new ResultSetException("获取结果集中字段异常" + rs.toString() + "字段名：" +columnName, e);
        }
    }

    /**
     * 将对象转换为指定的目标对象
     * @param original resultset中的对象
     * @return 返回Date类型日期
     */
    @Deprecated
    private Date convertToDate(Object original){
        if(original.getClass() == java.sql.Date.class){
            return new Date(((java.sql.Date)original).getTime());
        }
        if(original instanceof Long){
            return new Date((long)original);
        }
        if(original.getClass() == Timestamp.class ){
            return new Date(((Timestamp)original).getTime());
        }

        if(original instanceof String){
            DateFormat dateFormat = new SimpleDateFormat();
            try {
                return dateFormat.parse((String)original);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new OrmException("类型转换异常" + e.getMessage());
            }
        }
        throw new OrmException("不支持的日期转换" + original.getClass().getSimpleName());
    }

}
